package ws

import (
	"github.com/gorilla/websocket"
)

type Protocol interface {
	NewCodec(conn *websocket.Conn) (Codec, error)
}

type ProtocolFunc func(conn *websocket.Conn) (Codec, error)

func (pf ProtocolFunc) NewCodec(conn *websocket.Conn) (Codec, error) {
	return pf(conn)
}

type Codec interface {
	Receive() (interface{}, error)
	Send(interface{}) error
	Close() error
}

type ClearSendChan interface {
	ClearSendChan(<-chan interface{})
}

func Listen(urlStr string, protocol Protocol, sendChanSize int, handler Handler) (*Server, error) {
	return NewServer(urlStr, protocol, sendChanSize, handler), nil
}

func Dial(urlStr string, protocol Protocol, sendChanSize int) (*Session, error) {
	conn, _, err := websocket.DefaultDialer.Dial(urlStr, nil)
	if err != nil {
		return nil, err
	}
	codec, err := protocol.NewCodec(conn)
	if err != nil {
		return nil, err
	}
	session := NewSession(codec, sendChanSize)
	session.remoteAddr = conn.RemoteAddr().String()
	return session, nil
}
